<template>
	<div class="content">
		<cl-crud @load="onLoad">
			<template #slot-top>
				<div class="bi-filter">
					<div
						class="bi-li"
						:class="[{ active: selects.status === 0 }]"
						@click="changeStatus(0)"
					>
						出售中商品
					</div>
					<div
						class="bi-li"
						:class="[{ active: selects.status === 1 }]"
						@click="changeStatus(1)"
					>
						仓库中商品
					</div>
					<div
						class="bi-li"
						:class="[{ active: selects.status === 2 }]"
						@click="changeStatus(2)"
					>
						售罄商品
					</div>
					<div
						class="bi-li"
						:class="[{ active: selects.status === 3 }]"
						@click="changeStatus(3)"
					>
						商品回收站
					</div>
				</div>
			</template>
			<template #slot-btn>
				<el-button
					type="danger"
					size="mini"
					@click="batchFiled(0)"
					:disabled="
						selectRow.length > 0 && (selects.status === 0 || selects.status === 1)
							? false
							: true
					"
					>批量下架</el-button
				>
				<el-button
					type="success"
					size="mini"
					@click="batchFiled(1)"
					:disabled="
						selectRow.length > 0 && (selects.status === 0 || selects.status === 1)
							? false
							: true
					"
					>批量上架</el-button
				>
			</template>
			<template #slot-filter>
				<div class="filter-list">
					<div class="filter-item">
						<span class="filter-title">分类：</span>
						<el-select
							size="mini"
							filterable
							placeholder="请选择分类"
							style="width: 140px"
							v-model="selects.firstClassify"
							@change="val => onClassifyChange(val, 'first')"
						>
							<el-option value label="全部"></el-option>
							<el-option
								:label="item.name"
								:value="item.id"
								v-for="item in options.firstClassify"
								:key="item.id"
							></el-option>
						</el-select>
					</div>
					<!--                    <div class="filter-item">-->
					<!--                        <span class="filter-title">二级分类：</span>-->
					<!--                        <el-select-->
					<!--                                class="filter-select"-->
					<!--                                size="mini"-->
					<!--                                filterable-->
					<!--                                placeholder="请选择二级分类"-->
					<!--                                style="width: 140px"-->
					<!--                                v-model="selects.secondClassify"-->
					<!--                                @change="val => onClassifyChange(val)"-->
					<!--                        >-->
					<!--                            <el-option :label="item.name" :value="item.id" v-for="item in options.secondClassify" :key="item.id"></el-option>-->
					<!--                        </el-select>-->
					<!--                    </div>-->
					<div class="filter-item">
						<span class="filter-title">销量：</span>
						<el-input-number
							v-model="selects.startSales"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
						<span style="font-size:16px;margin-right:0px"> - </span>
						<el-input-number
							v-model="selects.endSales"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
					</div>
					<div class="filter-item">
						<span class="filter-title">售价：</span>
						<el-input-number
							v-model="selects.startPrice"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
						<span style="font-size:16px;margin-right:0px"> - </span>
						<el-input-number
							v-model="selects.endPrice"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
					</div>
					<div class="filter-item">
						<span class="filter-title">成本：</span>
						<el-input-number
							v-model="selects.startCostprice"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
						<span style="font-size:16px;margin-right:0px"> - </span>
						<el-input-number
							v-model="selects.endCostprice"
							controls-position="right"
							style="width:80px;"
							size="mini"
						></el-input-number>
						<el-button style="margin-left:1em" size="mini" @click="onSearch()"
							>搜索</el-button
						>
						<el-button style="margin-left:1em" size="mini" @click="resetSearch()"
							>重置</el-button
						>
					</div>
				</div>
			</template>
			<template #slot-plat>
				<div class="filter-list">
					<div class="filter-item" style="margin-left: 66px">
						<el-button type="danger" size="mini" @click="onGoodsSync()"
							>同步丝路品</el-button
						>
					</div>
					<div class="filter-item">
						<span class="filter-title">平台：</span>
						<el-select
							size="mini"
							filterable
							placeholder="请选择平台"
							style="width: 140px"
							v-model="selects.plat"
							@change="
								val => {
									refresh({ app: val });
								}
							"
						>
							<el-option value label="全部"></el-option>
							<el-option label="自营" value="default"></el-option>
							<el-option label="丝路" value="silu"></el-option>
						</el-select>
					</div>
				</div>
			</template>
			<template #table-column-endprice="{ scope }">
				<div class="goods-info">
					<img :src="scope.row.pic" />
					<div class="goods-content">
						<p>{{ scope.row.title }}</p>
						<p class="price">
							售价：<span>¥{{ scope.row.endprice }}</span>
						</p>
						<p class="sort">
							分类：<span
								v-for="(classify, index) in scope.row.classifyNames"
								:key="index"
								>{{ classify }}</span
							>
						</p>
					</div>
				</div>
			</template>
			<template #table-column-level="{scope}">
				<el-input
					v-model="scope.row.level"
					size="mini"
					@change="e => onLevelChange(e, scope.row)"
				></el-input>
			</template>
			<template #table-column-status="{ scope }">
				<el-switch
					v-model="scope.row.status"
					active-text="上架"
					inactive-text="下架"
					:active-value="1"
					:inactive-value="0"
					@change="e => onSwitchChange(e, scope.row)"
				></el-switch>
			</template>
			<template #slot-operate="{ scope }">
				<el-button type="text" size="small" @click="onDelete(scope.row)">删除</el-button>
			</template>
		</cl-crud>
	</div>
</template>

<script>
// import fileListOne from '@/components/feilListOne';
import fileList from '@/components/feilList';
import SkuSelect from './components/SkuSelect';
import DetailMsg from './components/DetailMsg';
export default {
	name: 'banner',
	data() {
		return {
			crud: null,
			options: {
				firstClassify: []
				// secondClassify: []
			},
			selects: {
				status: 0,
				firstClassify: '',
				plat: ''
			},
			selectRow: [],
			defaultSort: {
				prop: 'createTime',
				order: 'descending'
			}
		};
	},
	created() {
		// 获取一级分类
		this.$service.goods.classify
			.list({
				parentId: 0
			})
			.then(res => {
				this.options.firstClassify = res;
			});
	},
	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.goods.manage)
				.set('search', {
					key: {
						placeholder: '请输入商品标题'
					}
				})
				.set('table', {
					columns: [
						{
							type: 'selection',
							label: '全选',
							align: 'center',
							width: '60px'
						},
						{
							label: '商品ID',
							prop: 'id',
							align: 'center',
							width: 100
						},
						{
							label: '商品描述（按售价排序）',
							prop: 'endprice',
							align: 'left',
							width: 350,
							sortable: 'custom'
						},
						{
							label: '平台',
							prop: 'app',
							align: 'center',
							dict: [
								{
									label: '自营',
									value: 'default'
								},
								{
									label: '丝路',
									value: 'silu'
								}
							]
						},
						{
							label: '销量',
							prop: 'sales',
							align: 'center'
						},
						{
							label: '库存',
							prop: 'stock',
							align: 'center'
						},
						{
							label: '成本',
							prop: 'costprice',
							align: 'center'
						},
						{
							label: '排序',
							prop: 'level',
							align: 'center',
							sortable: 'custom'
						},
						{
							label: '添加时间',
							prop: 'createTime',
							align: 'center',
							sortable: 'custom'
						},
						{
							label: '上架时间',
							prop: 'starttime',
							align: 'center'
						},
						{
							label: '状态',
							prop: 'status',
							align: 'center',
							width: 150
						}
					],
					op: {
						layout: ['edit', 'slot-operate']
					},
					props: {
						'default-sort': {
							prop: this.defaultSort.prop,
							order: this.defaultSort.order
						}
					},
					on: {
						'selection-change': selection => {
							this.selectRow = selection;
						}
					}
				})
				.set('upsert', {
					props: {
						title: '',
						width: '950px',
						labelWidth: '120px'
					},
					items: [
						{
							prop: 'title',
							label: '商品名称：',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写商品名称',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '商品名称不能为空'
								}
							]
						},
						{
							prop: 'classifyIds',
							label: '商品分类：',
							value: [],
							component: {
								name: 'el-select',
								options: [],
								attrs: {
									placeholder: '请选择商品分类',
									clearable: true,
									multiple: true
								}
							},
							rules: {
								required: true,
								message: '商品分类不能为空'
							}
						},
						{
							prop: 'brief',
							label: '商品简介：',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写商品简介',
									type: 'textarea',
									clearable: true
								}
							},
							rules: {
								required: true,
								message: '商品简介不能为空'
							}
						},
						{
							prop: 'pic',
							label: '商品封面图：',
							component: fileList,
							rules: {
								required: true,
								message: '封面图不能为空'
							}
						},
						{
							prop: 'rotationalPic',
							label: '商品轮播图：',
							component: fileList,
							rules: {
								required: true,
								message: '轮播图不能为空'
							}
						},
						{
							prop: 'specificationInfo',
							label: '商品规格：',
							component: SkuSelect,
							rules: [
								{
									validator: (rule, value, callback) => {
										if (!value) {
											callback(new Error('商品规格不能为空'));
										} else {
											let arr = JSON.parse(value);
											if (arr.skuInfo.length === 0) {
												callback(new Error('请选择规格模板'));
											}
											if (arr.specifications.length === 0) {
												callback(new Error('请生成规格列表'));
											}

											let flag = true;
											arr.skuInfo.forEach(item => {
												if (!item.name) {
													flag = false;
													callback(new Error('规格名不能为空'));
												}
												item.desc.split(',').forEach(desc => {
													if (!desc) {
														flag = false;
														callback(new Error('规格值不能为空'));
													}
												});
											});

											// 多规格
											if (arr.specifications.length > 1) {
												arr.specifications.forEach(item => {
													if (
														!item.endprice &&
														!item.costprice &&
														!item.price &&
														!item.surplus
													) {
														flag = false;
														callback(new Error('商品规格不能为空'));
													} else if (!item.endprice) {
														flag = false;
														callback(new Error('售价不能为空'));
													} else if (!item.costprice) {
														flag = false;
														callback(new Error('成本价不能为空'));
													} else if (!item.price) {
														flag = false;
														callback(new Error('原价不能为空'));
													} else if (!item.surplus) {
														flag = false;
														callback(new Error('库存不能为空'));
													}
												});
												if (flag) {
													callback();
												}
											} else {
												// 单规格
												arr.specifications.forEach(item => {
													if (
														!item.specification &&
														!item.endprice &&
														!item.costprice &&
														!item.price &&
														!item.surplus
													) {
														callback(new Error('商品规格不能为空'));
													} else if (!item.specification) {
														callback(new Error('规格不能为空'));
													} else if (!item.endprice) {
														callback(new Error('售价不能为空'));
													} else if (!item.costprice) {
														callback(new Error('成本价不能为空'));
													} else if (!item.price) {
														callback(new Error('原价不能为空'));
													} else if (!item.surplus) {
														callback(new Error('库存不能为空'));
													} else {
														callback();
													}
												});
											}
										}
									},
									required: true
								}
							]
						},
						{
							prop: 'freight',
							label: '运费模板：',
							value: 0,
							component: {
								name: 'el-select',
								options: [
									{
										label: '免运费',
										value: 0
									},
									{
										label: '5元',
										value: 5
									},
									{
										label: '6元',
										value: 6
									},
									{
										label: '8元',
										value: 8
									},
									{
										label: '10元',
										value: 10
									},
									{
										label: '12元',
										value: 12
									},
									{
										label: '15元',
										value: 15
									},
									{
										label: '20元',
										value: 20
									}
								],
								attrs: {
									placeholder: '请选择商品分类',
									clearable: true
								}
							},
							rules: {
								required: true,
								message: '商品分类不能为空'
							}
						},
						// {
						// 	prop: 'detailMsg',
						// 	label: '商品详情图：',
						// 	component: fileList,
						// 	rules: {
						// 		required: true,
						// 		message: '商品详情图不能为空'
						// 	}
						// },
						{
							prop: 'level',
							label: '排序：',
							value: 0,
							component: {
								name: 'el-input-number',
								attrs: {
									placeholder: '请输入排序',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '排序不能为空'
								}
							]
						},
						{
							prop: 'status',
							label: '商品状态：',
							value: 1,
							component: {
								name: 'el-radio-group',
								options: [
									{
										label: '上架',
										value: 1
									},
									{
										label: '下架',
										value: 0
									}
								]
							},
							rules: {
								required: true,
								message: '商品状态不能为空'
							}
						},
						{
							prop: 'detailMsg',
							label: '商品详情：',
							component: DetailMsg,
							rules: {
								required: true,
								message: '商品详情不能为空'
							}
						}
					]
				})
				.set('layout', [
					['slot-top'],
					['refresh-btn', 'add-btn', 'slot-btn', 'slot-filter', 'flex1', 'search-key'],
					['slot-plat'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('open', (isEdit, form) => {
					if (isEdit) {
						if (form.specifications.length === 0) {
							form.specifications = [
								{
									costprice: form.costprice,
									endprice: form.endprice,
									price: form.price,
									specification: JSON.parse(form.skuInfo)[0].desc,
									surplus: form.stock
								}
							];
						}
						app.setData('upsert.props.title', '编辑商品');
						app.setForm('classifyIds', form.classifyIds.split(','));
						app.setForm(
							'specificationInfo',
							JSON.stringify({
								operate: 'edit',
								skuInfo: form.skuInfo,
								specifications: form.specifications
							})
						);
						app.setForm(
							'detailMsg',
							JSON.stringify({
								operate: 'edit',
								detailMsg: form.detailMsg
							})
						);
					} else {
						app.setData('upsert.props.title', '新增商品');
					}
					// 获取二级分类
					let classify = [];
					this.options.firstClassify.forEach(item => {
						classify.push({
							label: item.name,
							value: item.id
						});
					});
					app.setData('upsert.items[prop:classifyIds].component.options', classify);
					// this.$service.goods.classify.list().then(res => {
					// 	res.forEach(item => {
					// 		classify.push({
					// 			label: item.name,
					// 			value: item.id
					// 		});
					// 	});
					// 	app.setData('upsert.items[prop:classifyIds].component.options', classify);
					// });
				})
				.on('submit', (isEdit, data, { next }) => {
					let specificationInfo = JSON.parse(data.specificationInfo);
					delete data.specificationInfo;
					next({
						...data,
						classifyIds: data.classifyIds.join(','),
						skuInfo: JSON.stringify(specificationInfo.skuInfo),
						specifications: JSON.stringify(specificationInfo.specifications)
					});
				})
				.on('refresh', async (params, { next, render }) => {
					const { list } = await next(params);
					render(list);
				})
				.done();
			app.refresh({
				status: 1,
				isDel: 0,
				surplus: 1
			});
		},
		refresh(params) {
			this.crud.refresh(params);
		},
		// 分类筛选
		onClassifyChange(val) {
			this.refresh({
				classifyId: val,
				page: 1
			});
			// if (level === 'first') {
			// 	// 获取二级分类
			// 	this.$service.goods.classify.list({
			// 		parentId: val
			// 	}).then(res => {
			// 		this.options.secondClassify = res;
			// 	});
			// }
		},
		changeStatus(active) {
			if (this.selects.status === active) {
				return false;
			}
			this.selects.status = active;
			if (active === 0) {
				this.refresh({
					status: 1,
					surplus: 1,
					isDel: 0
				});
			} else if (active === 1) {
				this.refresh({
					status: 0,
					surplus: null,
					isDel: 0
				});
			} else if (active === 2) {
				this.refresh({
					surplus: 0,
					status: null,
					isDel: 0
				});
			} else if (active === 3) {
				this.refresh({
					isDel: 1,
					surplus: null,
					status: null,
					isShow: null
				});
			}
		},
		// 批量操作
		batchFiled(status) {
			let idsArr = [];
			this.selectRow.forEach(item => {
				idsArr.push(item.id);
			});
			this.$service.comm
				.batchFiled({
					repository: 'goods',
					status: status,
					ids: idsArr.join(',')
				})
				.then(() => {
					this.crud.refresh();
				});
		},
		onLevelChange(e, item) {
			this.$service.goods.manage
				.update({
					id: item.id,
					level: e
				})
				.then(() => {
					this.crud.refresh();
				});
		},
		onSwitchChange(e, item) {
			this.$service.goods.manage
				.update({
					id: item.id,
					status: e
				})
				.then(() => {
					this.crud.refresh();
				})
				.catch(err => {
					this.$message.error(err);
				});
		},
		onSearch() {
			let params = {};
			if (this.selects.startSales) {
				params.startSales = this.selects.startSales;
			}
			if (this.selects.endSales) {
				params.endSales = this.selects.endSales;
			}
			if (this.selects.startPrice) {
				params.startPrice = this.selects.startPrice;
			}
			if (this.selects.endPrice) {
				params.endPrice = this.selects.endPrice;
			}
			if (this.selects.startCostprice) {
				params.startCostprice = this.selects.startCostprice;
			}
			if (this.selects.endCostprice) {
				params.endCostprice = this.selects.endCostprice;
			}

			this.crud.refresh(params);
		},
		resetSearch() {
			this.selects.firstClassify = 0;
			this.selects.startSales = 0;
			this.selects.endSales = 0;
			this.selects.startPrice = 0;
			this.selects.endPrice = 0;
			this.selects.startCostprice = 0;
			this.selects.endCostprice = 0;

			this.crud.refresh({
				classifyId: null,
				startSales: null,
				endSales: null,
				startPrice: null,
				endPrice: null,
				startCostprice: null,
				endCostprice: null
			});
		},
		onDelete(item) {
			this.$confirm('删除后将无法恢复，请谨慎操作', '您确定要删除这条信息吗？', {
				confirmButtonText: '立即删除',
				cancelButtonText: '考虑一下',
				type: 'warning'
			}).then(() => {
				this.$service.goods.manage
					.update({
						id: item.id,
						isDel: 1
					})
					.then(() => {
						this.crud.refresh();
					})
					.catch(err => {
						this.$message.error(err);
					});
			});
		},
		onGoodsSync() {
			this.$service.goods.manage.synSiLuGoods().then(() => {
				this.$message.success('同步成功');
				this.refresh();
			});
		}
	}
};
</script>

<style lang="stylus" scoped>
.content {
    .goods-info {
        flexBox(space-between, flex-start)
        img {
            width: 80px;
            height: 80px;
            margin-right 10px
        }
        .goods-content {
            flex: 1;
            .price {
                span {
                    color: $main-color
                }
            }
            .sort {
                span {
                    margin-right 20px
                }
            }
        }
    }
}
</style>
